package it.camelotone.controller;

import it.camelotone.ejb.entity.Friend;
import it.camelotone.ejb.session.SalutationLocal;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SportController
 */
@WebServlet("/SportController")
public class SportController extends HttpServlet {
	
	private static final String COUNT_ATTRIBUTE_NAME = "count";
	private static final long serialVersionUID = 1L;
	
	@EJB(beanName="Salutation")
	private SalutationLocal salutation;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SportController() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute(COUNT_ATTRIBUTE_NAME);
		int count = (Integer) ((attribute != null && attribute instanceof Integer) ? attribute : 0);
		session.setAttribute(COUNT_ATTRIBUTE_NAME, ++count);
		
		Friend firstFriend = salutation.getFirstFriend();
		
		PrintWriter out = response.getWriter();
		out.print("<html><body><h1>Request served at: ");
		out.print(request.getServletPath());
		out.print("</h1>");
		out.println("<p> Accessed again: " + count + "</p>");
		out.print("<p> My name is: " + firstFriend.getName() + "</p>");
		out.print("</body></html>");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
